package com.qn.auth;

import com.qn.util.RetFunction;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Token持久层接口实现
 *
 * @author Qning
 * @date 2022/05/13
 */
@Service
public class TokenDaoImpl implements TokenDao {
    @Resource
    public RedisTemplate<String, Object> objectRedisTemplate;

    @Override
    public void setObject(String key, Object value, long timeout) {
        objectRedisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    @Override
    public Object getObject(String key) {
        return objectRedisTemplate.opsForValue().get(key);
    }

    @Override
    public void deleteObject(String key) {
        objectRedisTemplate.delete(key);
    }

    @Override
    public Long getObjectTimeout(String key) {
        return objectRedisTemplate.getExpire(key);
    }

    @Override
    public void updateObjectTimeout(String key, long timeout) {
        objectRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
    }

    @Override
    public <T> T get(String key, RetFunction fun) {
        Object value = getObject(key);
        if (value == null) {
            value = fun.run();
            setObject(key, value, DEFAULT_EXPIRE);
        }
        return (T) value;
    }
}
